<!--  记得import .js中自定义的方法-->

<template>
  <div>
    <!--对话框    添加和更新用的 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="36%">     <!--  dialogFormVisible是自定义的弹窗名  -->
      <el-form :model="provider" :rules="providerRules" ref="providerRulesForm">

        <el-form-item label="序号" prop="id">
          <el-input v-model="provider.id" autocomplete="off" style="width:470px"></el-input>
        </el-form-item>

        <el-form-item label="供应商" prop="provider">
          <el-input v-model="provider.provider" autocomplete="off" style="width:498px"></el-input>
        </el-form-item>
        <br>
        <el-form-item label="网址" prop="website">
          <el-input v-model="provider.website" autocomplete="off" style="width:466px"></el-input>
        </el-form-item>

        <el-form-item label="联系人" prop="linkman">
          <el-input v-model="provider.linkman" autocomplete="off" style="width:498px"></el-input>
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="provider.phone" autocomplete="off" style="width:498px"></el-input>
        </el-form-item>

        <el-form-item label="qq" prop="qq">
          <el-input v-model="provider.qq" autocomplete="off" style="width:484px"></el-input>
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input v-model="provider.address" autocomplete="off" style="width:484px"></el-input>
        </el-form-item>

        <el-form-item label="跟进人" prop="followMan">
          <el-input v-model="provider.followMan" autocomplete="off" style="width:456px"></el-input>
        </el-form-item>

        <el-form-item label="创建时间" prop="createTime">
          <!--          <el-input v-model="provider.createTime" autocomplete="off" style="width:486px"></el-input>-->
          <el-date-picker
            v-model="pickedDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="操作" prop="control">
          <el-input v-model="provider.control" autocomplete="off" style="width:486px"></el-input>
        </el-form-item>


      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addProvider('providerRulesForm')">确 定</el-button>
      </div>
    </el-dialog>


    <!-- -=======================================================================================--=======================================================================================--==========================- -->
    <!--    上方按钮行-->
    <el-form :inline="true" :model="keyword" ref="searchForm" class="demo-form-inline"><!-- 最后加的keyword和searchForm -->
      <el-button type="danger" size="small" @click="delBatch" icon="el-icon-delete"
                 style="margin-left: 30px; margin-top: 3px">批量删除
      </el-button>

      <el-button type="warning" size="small" @click="openAddDialog" icon="el-icon-plus"
                 style="margin-left: 30px; margin-right: 30px; margin-top: 3px">添加供应商
      </el-button>
      <!--      111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111-->


      <el-select @change="handleSelect2" size="small" v-model="value" clearable placeholder="请选择"
                 style="padding: 5px 10px;margin-right: 30px;">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>

      <el-form-item label="地址" prop="address" style="margin-top: 3px">
        <!--    clearable    输入框的右侧会显示一个清除按钮（通常是一个小图标）-->
        <el-input size="small" clearable v-model="keyword.address" placeholder="输入地址名搜索"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="search" icon="el-icon-search" style="margin-top: 6px">查询
        </el-button>
        <el-button type="primary" plain size="small" @click="resetSearchForm('searchForm')" icon="el-icon-refresh"
                   style="margin-top: 6px">重置
        </el-button>
      </el-form-item>
      <!--      111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111-->
    </el-form>


    <!-- 中间行数据栏 -->
    <el-table v-loading="loading" :data="payList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="25" align="center"/>
      <el-table-column label="序号" align="center" prop="id"/>
      <el-table-column label="供应商" align="center" prop="provider"/>
      <el-table-column label="网址" align="center" prop="website"/>
      <el-table-column label="联系人" align="center" prop="linkman"/>
      <el-table-column label="联系电话" align="center" prop="phone"/>
      <el-table-column label="qq" align="center" prop="qq"/>
      <el-table-column label="地址" align="center" prop="address"/>
      <el-table-column label="跟进人" sortable align="center" prop="followMan"/>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="操作" sortable align="center" prop="control"/>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">  <!-- 操作栏 -->
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.$index, scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页栏-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[6,8,10,200]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

  </div>
</template>


<script>
import row from "element-ui/packages/row";
// /////////////////      ///////////////////////////////////////
import {getList, delBatch, addProvider, edit, deleteById} from "@/api/provider";

export default {
  computed: {
    row() {
      return row
    }
  },
  methods: {
    fetchData() { // 获取数据
      // 组装查询参数
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        followMan: this.keyword.followMan,
        address: this.keyword.address,
        // measureName: this.keyword.measureName,
      }
      console.log("params: ", params);       // 内容:{pageNum: 1, pageSize: 6
      // getList是api/unit.js中自己
      getList(params).then(res => {
        let pageInfo = res.data;
        // console.log("pageInfo", pageInfo)
        this.loading = false;
        this.payList = pageInfo.list;
        // console.log("====>",this.payList)
        // list就是pageInfo中含所有属性的对象的集合
        //   对象的集合
        this.total = pageInfo.total
        console.log("使用以上参数发送请求, findAll查到共", this.total, "条数据")    // 打印总行数(不分页)

      })
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.fetchData()
    },
    // 多选框选中数据
    handleSelectionChange(selectionRowArr) {
      this.ids = [];
      // 选项行（选中改变得到选中的这一行数据）
      // console.log("装着n个对象的数组: ", selectionRowArr)
      // 数组里面还是数组
      for (let i = 0; i < selectionRowArr.length; i++) {
        this.ids.push(selectionRowArr[i].id)
        // selectionRow[i].planNumber // 元素.对象
      }
      // console.log("看看ids数组: (数字数组)", this.ids)
      // 该方法至此完成任务
    },


    handleSelect2(value) {   // 和下方options 一起使用
      console.log("你用选择器选中了：", value);
      this.pageNum = 1
      this.keyword.followMan = value;
      this.fetchData()
    },


    // 批量删除
    delBatch() {
      this.$confirm('是否确认删除序号为' + this.ids + '的数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发请求
        let idStr = this.ids.join(",");
        // 这行代码的目的是将this.ids数组中的所有元素转换成一个由逗号分隔的字符串
        // 例如，如果this.ids是[1, 2, 3]，那么执行这行代码后，idStr的值将会是"1,2,3"。
        // console.log("收到字符串idStr", idStr)
        let params = {
          ids: idStr

        }
        // console.log("打印ids看到底是啥", params.ids,
        //   "据此后端写的是接受Integer数组,如果是选中字符串列删除，要改后端泛型")
        delBatch(params).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功',
            duration: 500,
          });
          this.fetchData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
          duration: 500,
        });
      });
    },


    // 添加，，，小弹窗   ，，方法
    // 打开添加对话框
    openAddDialog() {
      this.title = '添加';
      this.dialogFormVisible = true;
    },

    addProvider(formName) {
      this.confirmDate(); // 调用方法
      this.$refs[formName].validate((valid) => {   // valid是个布尔值, => 后面是提交表格校验返回true时向后执行的代码
        if (valid) {
          // 上面是校验通过
          // 此处执行添加
          console.log("添加status", this.provider)
          if (this.title === '添加') {
            addProvider(this.provider).then(res => {
              this.$message({
                type: 'success',
                message: '添加成功',
              });
              this.fetchData()
              this.$refs[formName].resetFields();
            })
          } else if (this.title === '编辑') {
            edit(this.provider).then(res => {
              this.$message({
                type: 'success',
                message: '修改成功',
              });
              this.fetchData()
              this.$refs[formName].resetFields();
            })
          }


        } else {
          console.log('error submit!!');
          return false;
        }
        this.dialogFormVisible = false;
      });
    },

    search() {
      this.pageNum = 1
      this.fetchData()
    },

    //   重置表单
    resetSearchForm(formName) {
      this.$refs[formName].resetFields();
      this.keyword.followMan = null;
      this.fetchData()
    },

    handleUpdate(a, b) {
      console.log("打印a（本页中, 此行的下标: ）", a);
      console.log("打印b（整行数据: ）", b);
      this.title = '编辑';
      this.provider = b;   // 回显
      this.dialogFormVisible = true;
    },

    // ID删除
    handleDelete(row) {
      console.log("接收到选中的id为" + row);
      this.$confirm('是否确认删除序号为' + row.id + '的数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发请求
        let params = {
          id: row.id
        }
        deleteById(params).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功',
            duration: 1000,
          });
          this.fetchData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
          duration: 1000,
        });
      });
    },

    confirmDate() {
      // 处理日期确认逻辑
      console.log('选中的日期:', this.pickedDate);
      const date = new Date(this.pickedDate);
      this.provider.createTime = date.toISOString().slice(0, 19).replace('T', ' '); // 返回格式化后的字符串
    }

  },
  name: "Provider",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 单位表格数据
      payList: [],
      pageNum: 1,
      pageSize: 6,
      currentPage: 1,
      total: 0,
      ids: [],
      keyword: {
        address: null,
        followMan: null,
        // measureName: null,
      },
      title: '',
      dialogFormVisible: false,
      inputValue: '',  // 在data()中声明inputValue，用于存储<el-autocomplete>的输入值
      restaurants: [],
      state1: '',
      state2: '',
      pickedDate: '',
      provider: {
        id: null,
        provider: null,
        website: null,
        linkman: null,
        phone: null,
        qq: null,
        address: null,
        followMan: null,
        createTime: null,
        control: null,
        //   写不写scope.row都能获得整行数据，包括未显示的
      },

      options: [{
        value: 'xxx',
      }, {
        value: '小狗',
      }, {
        value: '小花',
      },

      ],
      value: '',

      // rule1
      // rule
      // rule
      // rule
      providerRules: {
        id: [
          {required: true, message: '序号不能为空', trigger: 'blur'},
        ],
        linkman: [
          {required: true, message: '联系人不能为空', trigger: 'blur'},
        ],
        address: [
          {required: true, message: '地址不能为空', trigger: 'blur'},
        ],

      },


    }
  },
  created() {
    this.fetchData()
  },
}
</script>


<style scoped>

</style>
